from flask import Flask, request, render_template, send_from_directory, jsonify
from utils import ArgumentParser, ConfigLoader, LOG
from model import GLMModel, OpenAIModel
from translator import PDFTranslator
import random
import os

app = Flask(__name__)

# 设置上传文件的目录
UPLOAD_FOLDER = os.path.dirname(os.path.abspath(__file__)) + "/../uploads"
UPLOAD_FOLDER = os.path.abspath(UPLOAD_FOLDER)

app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['TEMPLATES_AUTO_RELOAD'] = True


if not os.path.exists(UPLOAD_FOLDER):
    os.makedirs(UPLOAD_FOLDER)

@app.route('/')
def index():
    return render_template('index.html')
@app.route('/images/<filename>')
def images(filename):
    return send_from_directory(os.path.dirname(os.path.abspath(__file__)) + "/../images", filename, as_attachment=True)

@app.route('/translate', methods=['POST'])
def translate():
    # 检查是否有文件在请求中
    if 'file' not in request.files:
        return jsonify({'error': 'No file part'})

    file = request.files['file']
    if file.filename == '':
        # 返回json
        return jsonify({'error': 'No selected file'})
    
    # 随机数生成，如果小于 0.5 则返回错误
    
    
    # if random.random() < 0.4:
    #     return jsonify({'error': 'Random error'})
    
    if not file.filename.lower().endswith('.pdf'):
        return jsonify({'error': 'Only PDF files are supported'})


    if file:
        filepath = os.path.join(app.config['UPLOAD_FOLDER'], file.filename)
        
        file.save(filepath)
        
        # 这里是处理文件的伪代码部分
        # markdown_content = "这里是翻译后的 Markdown 内容"

        # 新文件名添加_translated
        markdown_file = file.filename.rsplit('.', 1)[0] + '_translated.md'

        # 保存 Markdown 文件
        #markdown_file = file.filename.rsplit('.', 1)[0] + '.md'
        # markdown_path = os.path.join(app.config['UPLOAD_FOLDER'], markdown_file)
        # with open(markdown_path, 'w') as f:
        #     f.write(markdown_content)



        # argument_parser = ArgumentParser()
        # args = argument_parser.parse_arguments()
        # config_loader = ConfigLoader(args.config)

        # config = config_loader.load_config()

        model_name = 'gpt-3.5-turbo'
        api_key = os.environ.get('OPENAI_API_KEY') # if env.get('OPENAI_API_KEY') else config['OpenAIModel']['api_key']
        model = OpenAIModel(model=model_name, api_key=api_key)


        pdf_file_path = filepath
        file_format = 'markdown'

        # 实例化 PDFTranslator 类，并调用 translate_pdf() 方法
        translator = PDFTranslator(model)
        translator.translate_pdf(pdf_file_path, file_format)

        # 返回 Markdown 文件的下载链接
        return jsonify({'file': markdown_file, 'url': f'/downloads/{markdown_file}', 'error': ''})
        # return f'<a href="/downloads/{markdown_file}">Download Markdown file</a>'

@app.route('/downloads/<filename>')
def download_file(filename):
    return send_from_directory(app.config['UPLOAD_FOLDER'], filename, as_attachment=True)

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', port=5000)
